﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BLL;
using Entities;
using DAL;
using System.Data.SqlClient;
using System.Configuration;
using BLToolkit.Data;
using System.Collections;


namespace CuaHangBangDia.DoanhThu
{
    public partial class CapNhatDTTheoNgayForm : Form
    {
        
        double t = 0;
        int item = 12;
        int page = 1;
        int tong;
        bool _selectAll = false;
        List<string> xoa = new List<string>();
        int iCellHeight, iHeaderHeight;
        double iTotalWidth;
        bool bNewPage, bFirstPage;
        StringFormat strFormat;
        ArrayList arrColumnWidths = new ArrayList();
        ArrayList arrColumnLefts = new ArrayList();
        int iCount;
        
        public CapNhatDTTheoNgayForm()
        {
            InitializeComponent();
        }
        private void LoadDTTheoNgay(List<DoanhThuTheoNgay> ds)
        {
            dtLoad.DataSource = ds;
            tong = TongTrang(DoanhThuTheoNgay.Objects.GetAll().ToList().Count, item);
            txtTrang.Text = Convert.ToString(page);
            lbTongTrang.Text = "/ " + tong;

        }

        public List<DoanhThuTheoNgay> getPage(int page)
        {
            dtLoad.Columns[1].DefaultCellStyle.Format = "dd/MM/yyyy";
            var query = from c in DoanhThuTheoNgay.Objects.GetAll().ToList()
                           .Skip(item * page - item).Take(item)
                        select c;
            return query.ToList();

        }

        public static int TongTrang(int soluongdl, int num)
        {
            int kq = (int)(soluongdl / num);
            if (kq * num == soluongdl)
                return kq;
            return kq + 1;
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (page < tong)
                page++;
            if (page <= tong)
            {
                txtTrang.Text = Convert.ToString(page);
                LoadDTTheoNgay(getPage(page));
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            if (page >= 2)
            {
                page--;
                txtTrang.Text = Convert.ToString(page);
                LoadDTTheoNgay(getPage(page));
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            LoadDTTheoNgay(DoanhThuTheoNgay.Objects.GetAll().ToList());
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnHuy_Click(object sender, EventArgs e)
        {
            if (dtLoad.Rows.Count > 0)
            {
                for (int i = 0; i < dtLoad.Rows.Count; i++)
                {
                    
                    dtLoad.Rows[i].Cells[0].Value = null;

                }
            }
        }

        private void dtLoad_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            int n = dtLoad.Rows.Count;
            if (e.ColumnIndex == 0 && n > 0)
            {
                _selectAll = !_selectAll;
                for (int i = 0; i < n; i++)
                {
                    dtLoad.Rows[i].Selected = _selectAll;
                    dtLoad.Rows[i].Cells[0].Value = _selectAll;
                }


            }
        }
        private List<DoanhThuTheoNgay> LoadDoanhThu()
        {
            
            List<DoanhThuTheoNgay> ss = new List<DoanhThuTheoNgay>();
            List<string> q = new List<string>();
            List<BanHang> bh = BanHang.Objects.GetAll().ToList();
            List<NhapHang> nh = NhapHang.Objects.GetAll().ToList();
            foreach (BanHang i in bh)
            {
                foreach (NhapHang j in nh)
                {
                    if (i.NgayBan == j.NgayNhap)
                    {
                        DoanhThuTheoNgay dttn = new DoanhThuTheoNgay();
                        dttn.Ngay = i.NgayBan;
                        dttn.TienBanHang = i.Tong;
                        dttn.NhapHang = j.TongTien;                        
                        dttn.TongDoanhThuTheoNgay = j.TongTien + i.Tong;
                        if (!q.Contains(dttn.Ngay.ToString()))
                        {
                            q.Add(dttn.Ngay.ToString());
                            ss.Add(dttn);
                        }
                        

                    }
                    else
                    {
                        DoanhThuTheoNgay dttn = new DoanhThuTheoNgay();
                        dttn.Ngay = i.NgayBan;
                        dttn.TienBanHang = i.Tong;
                        dttn.NhapHang = 0;                        
                        dttn.TongDoanhThuTheoNgay = i.Tong;
                        if (!q.Contains(dttn.Ngay.ToString()))
                        {
                            q.Add(dttn.Ngay.ToString());
                            ss.Add(dttn);
                        }
                    }
                }
                
            }
            return ss;
            
        }

        private void frmCapNhatDTTheoNgay_Load(object sender, EventArgs e)
        {
            
            DoData();
            LoadDTTheoNgay(DoanhThuTheoNgay.Objects.GetAll().ToList());           
            
        }

        private void DoData()
        {
            foreach (DoanhThuTheoNgay s in LoadDoanhThu())
            {
                
                if (!KiemTraKhoaChinh(s.Ngay) && !xoa.Contains(s.Ngay.ToShortDateString()))
                {
                    DoanhThuTheoNgay.Objects.Insert(s);
                }

            }
        }
        private bool KiemTraKhoaChinh(DateTime dt)
        {

            foreach (var s in DoanhThuTheoNgay.Objects.GetAll())
            {
                if (s.Ngay.ToShortDateString().Equals(dt.ToShortDateString()))
                {
                       return true; 
                }
            }
            return false;
        }
        //private bool KiemTraKhoaChinh(string chuoi)
        //{

        //    foreach (var s in DoanhThuTheoNgay.Objects.GetAll())
        //    {
        //        if (s.Thang.Equals(chuoi))
        //        {

        //            return true;
        //        }
        //    }
        //    return false;
        //}
        private bool KiemTraNull(object a, object b)
        {

            if ((a == null && b == null) || a == null || b == null)
            {
                MessageBox.Show("Nhập Giá Trị cho Tiền Bán và Tiền Cho Thuê");
                return true;
            }
            return false;
        }
        private bool KiemTraNhapSo(object a)
        {

            if (a is String || a is Char)
            {
                MessageBox.Show("Nhập Giá Trị Là Số");
                return true;
            }

            return false;
        }
        private DoanhThuTheoNgay Getdata(int i)
        {
            
            DoanhThuTheoNgay dttn = new DoanhThuTheoNgay();
            dttn.Ngay = Convert.ToDateTime(dtLoad.Rows[i].Cells[2].Value);
            dttn.TienBanHang = Convert.ToDouble(dtLoad.Rows[i].Cells[3].Value);
            dttn.NhapHang = Convert.ToDouble(dtLoad.Rows[i].Cells[4].Value);
            dttn.TongDoanhThuTheoNgay = Convert.ToDouble(dtLoad.Rows[i].Cells[5].Value);
            return dttn;
        }

        private void dtLoad_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            string ten = dtLoad.Columns[e.ColumnIndex].Name;
            if (ten == "btnXoa")
            {
                for (int i = 0; i < dtLoad.Rows.Count; i++)
                {
                    if (dtLoad.Rows[i].Cells[0].Value!=null)
                    {
                        DoanhThuTheoNgay t = Getdata(i);
                        xoa.Add(t.Ngay.ToShortDateString());
                        if (DoanhThuTheoNgay.Objects.Delete(t))
                        {
                            
                            MessageBox.Show("Xóa Thành Công","Thông Báo");                         
                            btnLoad.PerformClick();
                        }
                    }
                }
            }
        }
        public void TimTheoNgay(DateTime dt)
        {
            List<DoanhThuTheoNgay> kq = DoanhThuTheoNgay.Objects.Find(b => b.Ngay.Equals(dt.ToString("MM/dd/yyyy"))).ToList();
            if (kq.Count > 0)
            {
                LoadDTTheoNgay(kq);
            }
            else
            {
                
                MessageBox.Show("Không Tìm Thấy", "Thông Báo");

            }
        }
        private void TimTheoThang(DateTime dt)
        {

            List<DoanhThuTheoNgay> kq = DoanhThuTheoNgay.Objects.Find(b => b.Ngay.Year == (dt.Year) && b.Ngay.Month == (dt.Month)).ToList();
            if (kq.Count > 0)
            {
                LoadDTTheoNgay(kq);
                foreach (var s in kq)
                {
                    label1.Text = "Tổng Doanh Thu Tháng : " + Convert.ToString(s.Ngay.Month + " / " + s.Ngay.Year) ;
                }
                TinhTong();
            }
            else
            {
               
                label1.Text = "";
                label3.Text = "";
                MessageBox.Show("Không Tìm Thấy", "Thông Báo");

            }
        }
        private void TimTheoNam(DateTime dt)
        {
            List<DoanhThuTheoNgay> kq = DoanhThuTheoNgay.Objects.Find(b => b.Ngay.Year == dt.Year).ToList();
            if (kq.Count > 0)
            {
                LoadDTTheoNgay(kq);
                foreach (var s in kq)
                {
                    label1.Text = "Tổng Doanh Thu Năm :" + Convert.ToString(s.Ngay.Year);
                }
                TinhTong();
                
            }
            else
            {
                
                MessageBox.Show("Không Tìm Thấy", "Thông Báo");

            }
        }
        private void TinhTong()
        {
            double tong = 0;
            for (int i = 0; i < dtLoad.Rows.Count; i++)
            {
                tong += Convert.ToDouble(dtLoad.Rows[i].Cells[4].Value);
            }
            label3.Text = tong.ToString() +" VND";
        }

        private void btnTK_Click(object sender, EventArgs e)
        {
            if (rbNgay.Checked)
            {
                TimTheoNgay(dtpNgayNhap.Value);
            }
            else if (rbThang.Checked)
            {
                TimTheoThang(dtpNgayNhap.Value);
               
            }
            else if (rbNam.Checked)
            {
                TimTheoNam(dtpNgayNhap.Value);
            }
            else
            {
                MessageBox.Show("Chọn Kiểu Tìm Kiếm", "Thông Báo");
            }
        }

        private void txtTrang_KeyPress(object sender, KeyPressEventArgs e)
        {
             
        }

        private void txtTrang_KeyDown(object sender, KeyEventArgs e)
        {
            int t;
            if (e.KeyData == Keys.Enter)
            {
                try
                {
                    t = Convert.ToInt32(txtTrang.Text);
                    if (t <= tong && t > 0)
                    {
                        LoadDTTheoNgay(getPage(t));
                        txtTrang.Text = Convert.ToString(t);
                        page = t;
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Nhâp Trang Muốn Đến");
                }

            }
        
        
        }

        private void btnIn_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog printDialog = new PrintPreviewDialog();
            printDialog.Document = printDocument1;
            if (DialogResult.OK == printDialog.ShowDialog())
            {

                printDocument1.DocumentName = "Test Page Print";
                printDocument1.Print();

            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            int iRow = 0;


            try
            {
                //Set the left margin
                int iLeftMargin = e.MarginBounds.Left - 25;
                //Set the top margin
                int iTopMargin = e.MarginBounds.Top;
                //Whether more pages have to print or not
                bool bMorePagesToPrint = false;
                int iTmpWidth = 0;
                int iCount = 0;

                //For the first page to print set the cell width and header height
                if (bFirstPage)
                {

                    for (int k = 0; k < dtLoad.ColumnCount; k++)
                    {


                        iTmpWidth = (int)(Math.Floor((double)((double)dtLoad.Columns[k].Width + 15 /
                        (double)iTotalWidth * (double)iTotalWidth *
                        ((double)e.MarginBounds.Width / (double)iTotalWidth))));
                        iTmpWidth = (int)(Math.Floor((double)((double)dtLoad.Columns[k].Width /
                            (double)iTotalWidth * (double)iTotalWidth *
                            ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                        iHeaderHeight = (int)(e.Graphics.MeasureString(dtLoad.Columns[k].HeaderText,
                            dtLoad.Columns[k].InheritedStyle.Font, iTmpWidth).Height) + 11;

                        // Save width and height of headers
                        arrColumnLefts.Add(iLeftMargin);
                        arrColumnWidths.Add(iTmpWidth);
                        iLeftMargin += iTmpWidth;

                    }
                }

                //Loop till all the grid rows not get printed
                while (iRow <= dtLoad.Rows.Count - 1)
                {
                    DataGridViewRow GridRow = dtLoad.Rows[iRow];
                    //Set the cell height
                    iCellHeight = GridRow.Height + 10;

                    //Check whether the current page settings allows more rows to print
                    if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                    {
                        bNewPage = true;
                        bFirstPage = false;
                        bMorePagesToPrint = true;
                        break;
                    }
                    else
                    {
                        if (bNewPage)
                        {
                            //Draw Header
                            e.Graphics.DrawString("Doanh Thu Theo Ngày",
                                new Font(dtLoad.Font, FontStyle.Bold),
                                Brushes.Black, e.MarginBounds.Left,
                                e.MarginBounds.Top - e.Graphics.MeasureString("Doanh Thu Theo Ngày",
                                new Font(dtLoad.Font, FontStyle.Bold),
                                e.MarginBounds.Width).Height - 13);

                            String strDate = DateTime.Now.ToLongDateString() + " " +
                                DateTime.Now.ToShortTimeString();
                            //Draw Date
                            e.Graphics.DrawString(strDate,
                                new Font(dtLoad.Font, FontStyle.Bold), Brushes.Black,
                                e.MarginBounds.Left +
                                (e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
                                new Font(dtLoad.Font, FontStyle.Bold),
                                e.MarginBounds.Width).Width),
                                e.MarginBounds.Top - e.Graphics.MeasureString("Doanh Thu Theo Ngày",
                                new Font(new Font(dtLoad.Font, FontStyle.Bold),
                                FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                            //Draw Columns                 
                            iTopMargin = e.MarginBounds.Top;

                            for (int l = 0; l < dtLoad.Columns.Count; l++)
                            {

                                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawRectangle(Pens.Black,
                                    new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight));

                                e.Graphics.DrawString(dtLoad.Columns[l].HeaderText,
                                    dtLoad.Columns[l].InheritedStyle.Font,
                                    new SolidBrush(dtLoad.Columns[l].InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                                    (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                                iCount++;

                            }
                            bNewPage = false;
                            iTopMargin += iHeaderHeight;
                        }
                        iCount = 0;
                        for (int t = 0; t < GridRow.Cells.Count; t++)
                        {

                            if (GridRow.Cells[t].Value != null)
                            {
                                e.Graphics.DrawString(GridRow.Cells[t].Value.ToString(),
                                    GridRow.Cells[t].InheritedStyle.Font,
                                    new SolidBrush(GridRow.Cells[t].InheritedStyle.ForeColor),
                                    new RectangleF((int)arrColumnLefts[iCount],
                                    (float)iTopMargin,
                                    (int)arrColumnWidths[iCount], (float)iCellHeight),
                                    strFormat);
                            }
                            //Drawing Cells Borders 
                            e.Graphics.DrawRectangle(Pens.Black,
                                new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                (int)arrColumnWidths[iCount], iCellHeight));
                            iCount++;

                        }
                    }

                    iRow++;
                    iTopMargin += iCellHeight;
                }
                //If more lines exist, print another page.
                if (bMorePagesToPrint)
                    e.HasMorePages = true;
                else
                    e.HasMorePages = false;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
                   MessageBoxIcon.Error);
            }
        }

        private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            try
            {
                strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Near;
                strFormat.LineAlignment = StringAlignment.Center;
                strFormat.Trimming = StringTrimming.EllipsisCharacter;

                arrColumnLefts.Clear();
                arrColumnWidths.Clear();
                iCellHeight = 0;
                iCount = 0;
                bFirstPage = true;
                bNewPage = true;

                // Calculating Total Widths
                iTotalWidth = 0;

                for (int k = 0; k < dtLoad.Columns.Count; k++)
                {
                    iTotalWidth += dtLoad.Columns[k].Width - 12;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        
    }
}
